import { defineStore } from 'pinia'
import { ref } from 'vue'
import { request } from '@/utils/request'

export const useUserStore = defineStore('user', () => {
    const token = ref(localStorage.getItem('token') || '')
    const userId = ref('')
    const username = ref('')
    const email = ref('')
    const avatar = ref('')
    const role = ref('')

    // 登录
    const login = async (credentials: { email: string; password: string }) => {
        try {
            const response = await request.post('/auth/login', credentials)
            const { token: newToken, user } = response

            // 保存 token 到 localStorage
            localStorage.setItem('token', newToken)
            token.value = newToken

            // 更新用户信息
            userId.value = user.id
            username.value = user.username
            email.value = user.email
            avatar.value = user.avatar || ''
            role.value = user.role

            return response
        } catch (error) {
            console.error('Login failed:', error)
            throw error
        }
    }

    // 登出
    const logout = () => {
        localStorage.removeItem('token')
        token.value = ''
        userId.value = ''
        username.value = ''
        email.value = ''
        avatar.value = ''
        role.value = ''
    }

    // 获取用户信息
    const getUserInfo = async () => {
        try {
            const response = await request.get('/users/me')
            const user = response

            userId.value = user.id
            username.value = user.username
            email.value = user.email
            avatar.value = user.avatar || ''
            role.value = user.role

            return user
        } catch (error) {
            console.error('Failed to get user info:', error)
            logout()
            throw error
        }
    }

    return {
        token,
        userId,
        username,
        email,
        avatar,
        role,
        login,
        logout,
        getUserInfo
    }
}) 